<template>
  <div id="goods">


    <!--条件查询-->
    <el-form :inline="true" :model="searchObj" ref="formList" class="demo-form-inline">
      <el-form-item label="商品名称">
        <el-input v-model="searchObj.name" placeholder="请输入商品名称"></el-input>
      </el-form-item>
      <el-form-item label="上下架">
        <el-select v-model="searchObj.status" placeholder="请选择" clearable>
          <el-option
              v-for="item in shangXiaJia"
              :key="item.value"
              :label="item.label"
              :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="一级分类">
        <el-select v-model="firstKind" placeholder="请选择" clearable>
          <el-option
              v-for="item in firstKindList"
              :key="item.id"
              :label="item.categoryName"
              :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="二级分类">
        <el-select v-model="secondKind" placeholder="请选择" clearable>
          <el-option
              v-for="item in secondKindList"
              :key="item.id"
              :label="item.categoryName"
              :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="queryBtn">查询</el-button>
        <el-button @click="resetForm('formList')">
          <i class="el-icon-refresh-right"></i>
          重置
        </el-button>
      </el-form-item>
    </el-form>

    <!--新增-->
    <el-button type="primary" plain @click="addBtn">
      <i class="el-icon-user-solid"></i>
      新增
    </el-button>
    <el-button type="warning" plain @click="delsBtn">
      <i class="el-icon-delete-solid"></i>
      批量删除
    </el-button>

    <!--添加库存-->
    <el-dialog
            title="添加库存"
            :visible.sync="dialogVisible"
            width="30%"
            :before-close="handleClose"
            >
          <span>当前库存:{{ this.amount }}</span>
          <p>请输入要添加的数量</p>
          <el-input-number v-model="newStockUp" :min="1" :max="this.amount - this.stockUp"></el-input-number>
          <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addStockUp">确 定</el-button>
      </span>
    </el-dialog>

    <!--数据表格-->
    <el-table
        ref="multipleTable"
        :data="tableData"
        tooltip-effect="dark"
        style="width: 100%"
        @selection-change="handleSelectionChange">
      <el-table-column
          type="selection"
          width="55">
      </el-table-column>
      <el-table-column
          prop="goodsInfo.id"
          label="编号">
      </el-table-column>
      <el-table-column
          prop="imgLink"
          label="商品图片">
        <template slot-scope="scope">
          <el-avatar :size="45" shape="square" :src="scope.row.imgLink" @error="errorHandler">
            <img src="https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png"/>
          </el-avatar>
        </template>
      </el-table-column>
      <el-table-column
          prop="goodsInfo.name"
          label="商品名称">
      </el-table-column>
      <el-table-column
          label="类型">g
        <template slot-scope="scope">
          <span>{{ getType(scope.row.goodsInfo.goodsCategoryId) }}</span>
        </template>
      </el-table-column>
      <el-table-column
          prop="goodsInfo.unit"
          label="单位">
      </el-table-column>
      <el-table-column
          prop="goodsInfo.price"
          label="单价">
      </el-table-column>
      <el-table-column
          prop="goodsInfo.stockUp"
          label="上架库存">
      </el-table-column>
      <el-table-column
          prop="status"
          label="(下架/上架)">
        <template slot-scope="scope">
          <el-switch
              v-model="scope.row.goodsInfo.status"
              active-color="#13ce66"
              inactive-color="#ff4949"
              :active-value="1"
              :inactive-value="0"
              @change="switchStatus(scope.row.goodsInfo)"
              :disabled="scope.row.goodsInfo.stockUp <= 0"
          >
          </el-switch>
        </template>
      </el-table-column>

      <el-table-column
          label="操作">
        <template slot-scope="scope">
          <el-button
              @click="addStock(scope.row.goodsInfo)"
              type="text"
              size="small"
              icon="el-icon-plus">
            添加库存
          </el-button>
          <el-button
              @click="updateGoods(scope.row.goodsInfo.id)"
              type="text"
              size="small"
              icon="el-icon-edit">
            修改
          </el-button>
          <el-button
              @click="delGoods(scope.row.goodsInfo)"
              type="text"
              size="small"
              icon="el-icon-delete">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!--分页组件-->
    <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="pageSizeList"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
    </el-pagination>
  </div>
</template>

<script>
export default {
  name: "Goods",
  data() {
    return{
      //当前库存
      amount:'',

      //添加库存数量
      newStockUp:1,

      //添加库存的商品上架数量
      stockUp:0,

      //添加库存的商品Id
      goodsId:'',

      //添加库存对话框
      dialogVisible: false,

      //一级类别
      firstKindList: [],
      //二级类别
      secondKindList: [],
      //上下架下拉框
      shangXiaJia: [
        {
          value: 1,
          label: '上架'
        },
        {
          value: 0,
          label: '下架'
        },
      ],
      //商品类型级别
      goodsTypeLevel: [],
      //批量选中的row
      multipleSelection: [],
      //查询条件对象
      searchObj: {
        name: "",
        status: "",
        goodsCategoryId: "",
      },
      firstKind: "",
      secondKind: "",
      // 当前页号
      currentPage: 1,
      // 当前页大小
      pageSize: 5,
      // 总记录数
      total: 10,
      // 页大小列表
      pageSizeList: [2, 5, 10, 20],
      // 返回数据对象
      tableData: [],

      // 商品类型列表
      goodsTypeList: [],
    }
  },
  methods:{
    //关闭添加库存对话框
    handleClose() {
      this.dialogVisible = false;
      this.newStockUp = 1;
    },
    //添加上架库存的确定
    async addStockUp() {
      const { data : res } = await this.$http.post(`/goodsInfo/addStockUp/${this.newStockUp}/${this.goodsId}`);
      this.$message.success(res);
      this.dialogVisible = false;
      this.newStockUp = 1;
      this.queryBtn();
    },

    //上下架
    async switchStatus(goodsInfo) {
        const { data : res } = await this.$http.post('/goodsInfo/updateStatus',goodsInfo);
        this.$message.success(res);
    },
    //添加库存对话框
    async addStock(goodsInfo) {

      this.goodsId = goodsInfo.id;
      this.stockUp = goodsInfo.stockUp;

      const { data: res } = await this.$http.post(`/warehouseDetails/queryGoodsAmount/${this.goodsId}`);
      if(res == 0 )
        return this.$message.warning("当前库存为0,需要采购！");
      if(res == this.stockUp)
        return this.$message.warning("已上架全部库存！");
      this.dialogVisible = true;
      this.amount = res;
    },
    //类型
    getType(id) {
      let typeId = id.split("-");
      const data = this.goodsTypeList;
      let typeAry = [];
      for(let t=0;t<typeId.length;t++){
        for(let i=0;i<data.length;i++) {
          if(typeId[t] == data[i].id ) {
            typeAry.push(data[i].categoryName)
          }
        }
      }
      let typeName = typeAry.join('/')
      return typeName
    },
    //删除
    delGoods(row) {
      this.$confirm('是否确认删除？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        //确定
        const { data: res } = await this.$http.post(`/goodsInfo/delGoods`,row);
        this.$message.success(res);
        //界面刷新
        this.queryBtn();
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        });
      });
    },
    //批量删除
    delsBtn() {
      if(this.multipleSelection.length === 0)
        return this.$message.info("请先选中你要删除的商品！")
      this.$confirm('是否确认删除？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        //确定
        const { data: res } = await this.$http.post(`/goodsInfo/delsGoods`,this.multipleSelection);
        this.$message.success(res);
        //界面刷新
        this.queryBtn();
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        });
      });
    },
    //新增商品
    addBtn() {
      this.$router.push('/addGoods')
    },
    //修改商品
    updateGoods(id) {
      this.$router.push({ path: '/updateGoods', query: { id: id } })
    },
    //查询
    async queryBtn() {
      this.searchObj.goodsCategoryId = this.firstKind+"-"+this.secondKind
      const { data: res } = await this.$http.post(`/goodsInfo/getGoodsList/${this.currentPage}/${this.pageSize}`,this.searchObj);
      this.tableData = res.rows;
      this.total = res.total;
    },
    //重置
    resetForm(formName) {
      console.log(formName)
      console.log(this.$refs[formName])
      this.$refs[formName].resetFields();
    },
    //页大小改变
    handleSizeChange(val) {
      this.pageSize = val
      this.queryBtn()
    },
    //当前页改变
    handleCurrentChange(val){
      this.currentPage = val
      this.queryBtn()
    },
    //批量选择
    handleSelectionChange(val) {
      let ary=[];
      for(let i=0;i<val.length;i++){
        ary.push(val[i].goodsInfo)
      }
      this.multipleSelection = ary;
    },
    //头像展示失败
    errorHandler() {
      return true
    },
    //查询商品类型级别
    async queryGoodsTypeLevel() {
      const { data: res } = await this.$http.post(`/goodsCategory/queryGoodsTypeLevel`);
      this.goodsTypeLevel = res;
    },
    //商品类型列表
    async queryGoodsType() {
      const { data: res } = await this.$http.post(`/goodsCategory/queryGoodsCategoryList`);
      this.goodsTypeList = res
      for(let i=0;i<res.length;i++ ){
        if(res[i].level === 1){
          this.firstKindList.push(res[i])
        }
        if (res[i].level === 2){
          this.secondKindList.push(res[i])
        }
      }
    }
  },
  created() {
    //商品类型列表
    this.queryGoodsType();

    this.queryBtn();

    //查询商品类型级别
    this.queryGoodsTypeLevel();


  }
}
</script>

<style scoped>

</style>